//
//  ZCAbnormalLackViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/24.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCAbnormalLackViewController.h"
#import "ZCAbnormalModel.h"
#import "ZCAbnormalLackTableViewCell.h"
#import "ZCAbnormalWriteLackTableViewCell.h"

static NSString *missimgCellID = @"ZCAbnormalLackTableViewCell";
static NSString *writeLackCellID = @"ZCAbnormalWriteLackTableViewCell";

@interface ZCAbnormalLackViewController ()<UITableViewDelegate, UITableViewDataSource, ZCAbnormalWriteLackTableViewCellDelegate, ZCAbnormalLackTableViewCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *commitButton;
@property (nonatomic, strong) NSMutableArray *missingPartArray;
@property (nonatomic, copy) NSString *otherPart;
@property (nonatomic, copy) NSMutableString *missingPart;
@property (nonatomic, assign) BOOL isOtherPart;
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation ZCAbnormalLackViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - space(170)) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCAbnormalLackTableViewCell class] forCellReuseIdentifier:missimgCellID];
        [_tableView registerClass:[ZCAbnormalWriteLackTableViewCell class] forCellReuseIdentifier:writeLackCellID];
    }
    return _tableView;
}

- (NSArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

- (UIButton *)commitButton {
    if (!_commitButton) {
        _commitButton = [[UIButton alloc] init];
        [_commitButton setTitle:@"确认" forState:UIControlStateNormal];
        [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_commitButton setBackgroundColor:ZCColor(0xff8213, 1)];
        _commitButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(30)];
        _commitButton.layer.masksToBounds = YES;
        _commitButton.layer.cornerRadius = space(10);
        [_commitButton addTarget:self action:@selector(commitButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commitButton;
}

- (NSMutableArray *)missingPartArray {
    if (!_missingPartArray) {
        _missingPartArray = [NSMutableArray array];
    }
    return _missingPartArray;
}

- (NSMutableString *)missingPart {
    if (!_missingPart) {
        _missingPart = [NSMutableString string];
    }
    return _missingPart;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backToHome) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.title = @"标记缺件";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.commitButton];
    __weak typeof(self)weakSelf = self;
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
        make.height.mas_equalTo(space(170));
    }];
    
    [self.commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.bottomView.mas_left).offset(space(80));
        make.right.equalTo(weakSelf.bottomView.mas_right).offset(-space(80));
        make.top.equalTo(weakSelf.bottomView.mas_top).offset(space(40));
        make.bottom.equalTo(weakSelf.bottomView.mas_bottom).offset(-space(40));
    }];
    
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    
    [self loadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHiden:) name:UIKeyboardWillHideNotification object:nil];
    self.isOtherPart = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 键盘通知
- (void)keyboardWillShow:(NSNotification *)noti {
    CGRect rect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, rect.size.height - space(170), 0);
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.dataArray.count -1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)keyboardWillHiden:(NSNotification *)noti {
    self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
}

#pragma mark - 按钮点击
- (void)backToHome {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)commitButtonClick:(UIButton *)sender {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.taskType forKey:@"taskNode"];
    [param setObject:self.vin forKey:@"vin"];
    [param setObject:self.orderNo.length > 0 ? self.orderNo : @(0) forKey:@"orderNo"];
    [param setObject:self.taskId forKey:@"taskId"];
    __block NSMutableString *codes = [NSMutableString string];
    __block NSMutableString *names = [NSMutableString string];
    for (int i = 0; i < self.missingPartArray.count; i++) {
        ZCAbnormalMisssingPartModel *partModel = self.missingPartArray[i];
        if (i == 0) {
            [codes appendString:partModel.code];
            [names appendString:partModel.name];
            if ([partModel.code integerValue] == 5001001) {
                if (!self.isOtherPart) {
                    [self.missingPart appendString:partModel.describe];
                    self.otherPart = partModel.describe;
                }else {
                    [self.missingPart appendString:self.otherPart];
                }
            }else {
                [self.missingPart appendString:partModel.name];
            }
            
        }else {
            [codes appendString:@","];
            [codes appendString:partModel.code];
            [names appendString:@","];
            [names appendString:partModel.name];
            [self.missingPart appendString:@","];
            if ([partModel.code integerValue] == 5001001) {
                if (!self.isOtherPart) {
                    [self.missingPart appendString:partModel.describe];
                    self.otherPart = partModel.describe;
                }else {
                    [self.missingPart appendString:self.otherPart];
                }
            }else {
                [self.missingPart appendString:partModel.name];
            }
        }
    }

    [param setObject:codes.length > 0 ? codes : @"" forKey:@"codes"];
    [param setObject:names.length > 0 ? names : @"" forKey:@"names"];
    [param setObject:self.otherPart.length > 0 ? self.otherPart : @"" forKey:@"describe"];
    
    NSLog(@"%@",param);
    
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:EditMissingInfo params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                if (weakSelf.lackBlock) {
                    weakSelf.lackBlock(weakSelf.missingPart);
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            codes = nil;
            names = nil;
            weakSelf.missingPart = nil;
        }];
    });
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.taskType forKey:@"taskNode"];
    [param setObject:self.vin forKey:@"vin"];
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:MissingList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                NSMutableArray *tempA = [NSMutableArray array];
                NSArray *arr = responseObject[@"data"];
                for (NSDictionary *dic in arr) {
                    ZCAbnormalMissingModel *missingModel = [ZCAbnormalMissingModel yy_modelWithDictionary:dic];
                    for (ZCAbnormalMisssingPartModel *partM in missingModel.childComponent) {
                        partM.selected = [partM.isReigister boolValue];
                        if ([partM.isReigister boolValue]) {
                            [weakSelf.missingPartArray addObject:partM];
                        }
                    }
                    [tempA addObject:missingModel];
                }
                weakSelf.dataArray = [tempA copy];
                [weakSelf.tableView reloadData];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - ZCAbnormalLackTableViewCellDelegate
- (void)abnormalLackTableViewCellSelectLackButton:(UIButton *)sender missingModel:(ZCAbnormalMissingModel *)missingModel {
   
    for (ZCAbnormalMisssingPartModel *missingPartM in missingModel.childComponent) {
        if ([missingPartM.code integerValue]  == sender.tag) {
            if (sender.selected) {
                [self.missingPartArray addObject:missingPartM];
            }else {
                [self.missingPartArray removeObject:missingPartM];
            }
        }
    }
}

#pragma mark - ZCAbnormalWriteLackTableViewCellDelegate
- (void)abnormalWriteLackTableViewCellTextView:(NSString *)text missingModel:(ZCAbnormalMissingModel *)missingModel{
    self.isOtherPart = YES;
    self.otherPart = text;
    ZCAbnormalMisssingPartModel *missingPartM = [missingModel.childComponent firstObject];
    if ([missingPartM.code integerValue] == 5001001) {
        if (self.otherPart.length > 0) {
            missingPartM.selected = YES;
            for (ZCAbnormalMisssingPartModel *missM in self.missingPartArray) {
                if ([missM.code integerValue] == 5001001) {
                    [self.missingPartArray removeObject:missM];
                }
            }
            [self.missingPartArray addObject:missingPartM];
        }else {
            missingPartM.selected = NO;
            [self.missingPartArray removeObject:missingPartM];
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZCAbnormalMissingModel *missingM = (ZCAbnormalMissingModel *)self.dataArray[indexPath.section];
    
    if (indexPath.section == self.dataArray.count-1) {
        ZCAbnormalWriteLackTableViewCell *writeCell = [tableView dequeueReusableCellWithIdentifier:writeLackCellID forIndexPath:indexPath];
        writeCell.missingModel = missingM;
        writeCell.delegate = self;
        return writeCell;
    }else {
        ZCAbnormalLackTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:missimgCellID forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.missingModel = missingM;
        cell.delegate = self;
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == self.dataArray.count - 1) {
        return space(180);
    }
    ZCAbnormalMissingModel *missM = (ZCAbnormalMissingModel *)self.dataArray[indexPath.section];
    return missM.rowHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(80);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, space(80))];
    headerView.backgroundColor = ZCColor(0xf5f9fd, 1);
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(space(40), space(20), space(300), space(40))];
    titleLabel.textColor = ZCColor(0x000000, 0.54);
    titleLabel.font = [UIFont systemFontOfSize:FontSize(24)];
    ZCAbnormalMissingModel *missM = (ZCAbnormalMissingModel *)self.dataArray[section];
    titleLabel.text = missM.level1Name;
    [headerView addSubview:titleLabel];
    return headerView;
}

#pragma mark - 对象销毁
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
